package org.springblade.modules.oss.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author YuTao
 */

@Slf4j
public class ZipDownLoadUtil {
	private static final int ZIP_BUFFER_SIZE = 8192;


	/**
	 * zip打包下载
	 *
	 * @param response
	 * @param zipFileName
	 */
	public static void zipDownload(HttpServletResponse response, String zipFileName, List<URL> urls) {
		// zip文件路径
		String zipPath = System.getProperty("user.home") + "/Desktop/" + zipFileName;
		try {
			try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) {
				//声明文件集合用于存放文件
				byte[] buffer = new byte[1024];
				//将文件放入zip压缩包
				for (int i = 0; i < urls.size(); i++) {
					URL url = urls.get(i);
					System.out.println(url);

					try (InputStream fis = url.openStream()) {
						int f = url.toString().lastIndexOf("/");
						System.out.println(f);
						System.out.println(url.toString().substring(f));
						out.putNextEntry(new ZipEntry(url.toString().substring(url.toString().lastIndexOf("/"))));
						int len;
						// 读入需要下载的文件的内容，打包到zip文件
						while ((len = fis.read(buffer)) > 0) {
							out.write(buffer, 0, len);
						}
						out.closeEntry();
					}
				}
			}
			//下载zip文件
			downFile(response, zipFileName);
		} catch (Exception e) {
			log.error("文件下载出错", e);
		}
	}
	/**
	 * 文件下载
	 *
	 * @param response
	 * @param zipFileName
	 */
	private static void downFile(HttpServletResponse response, String zipFileName) {
		try {
			String path = System.getProperty("user.home") + "/Desktop/" + zipFileName;
			File file = new File(path);
			if (file.exists()) {
				try (InputStream ins = new FileInputStream(path);
					 BufferedInputStream bins = new BufferedInputStream(ins);
					 OutputStream outs = response.getOutputStream();
					 BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
					response.setContentType("application/x-download");
					response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
					int bytesRead = 0;
					byte[] buffer = new byte[ZIP_BUFFER_SIZE];
					while ((bytesRead = bins.read(buffer, 0, ZIP_BUFFER_SIZE)) != -1) {
						bouts.write(buffer, 0, bytesRead);
					}
					bouts.flush();
				}
			}
		} catch (Exception e) {
			log.error("文件下载出错", e);
		}
	}
}
